/* categoryDom */
var categoryDom = '\
<div class="box box-skin-inner sub-content">\
	<div class="box-header with-border">\
		<span class="box-title"></span>\
		<div class="box-tools pull-right">\
			<button type="button" class="btn btn-flat btn-box-tool btnCancel" data-widget="remove"><i class="fa fa-times"></i></button>\
		</div>\
	</div>\
	<div class="box-body">\
	<form class="form-horizontal" id="categoryForm">\
		<div class="row">\
			<div class="col-sm-12">\
				<div class="callout callout-default text-center" id="type">\
					<span>类型：</span>\
					<input type="radio" name="type" value="1" data-label="\<i class=\'fa fa-th-large\'\>\<\/i\> 栏目" checked />\
					<input type="radio" name="type" value="2" data-label="\<i class=\'fa fa-list\'\>\<\/i\> 列表" />\
					<input type="radio" name="type" value="3" data-label="\<i class=\'fa fa-file\'\>\<\/i\> 单页" />\
					<input type="radio" name="type" value="4" data-label="\<i class=\'fa fa-link\'\>\<\/i\> 外链" />\
				</div>\
			</div>\
		</div>\
		<div class="nav-tabs-custom no-margin" id="commonArea">\
		</div>\
	</form>\
	</div>\
	<div class="box-footer text-center">\
	    <button type="button" class="btn btn-info btn-flat btnOK">确定</button>\
	    <button type="button" class="btn btn-default btn-flat btnCancel">取消</button>\
	</div>\
</div>\
';

var commonAreaDom = '\
<ul class="nav nav-tabs">\
    <li class="active"><a href="#c1" data-toggle="tab" aria-expanded="true">基本信息</a></li>\
    <li class=""><a href="#c2" data-toggle="tab" aria-expanded="false">SEO设置</a></li>\
	<li class=""><a href="#c3" data-toggle="tab" aria-expanded="false">模型模版</a></li>\
	<li class=""><a href="#c4" data-toggle="tab" aria-expanded="false">静态化</a></li>\
</ul>\
<div class="tab-content">\
	<div class="tab-pane active" id="c1">\
		<div class="row">\
			<div class="col-sm-7">\
				<div class="form-group">\
					<label for="pidName" class="col-sm-2 control-label">分类</label>\
					<div class="col-sm-10">\
						<input type="hidden" id="pid" name="pid" />\
						<div class="input-group">\
						    <input type="text" class="form-control" id="pidName" name="pidName" disabled />\
							<span class="input-group-btn">\
								<button type="button" class="btn btn-info btn-flat" onclick="showMenu();">选择</button>\
							</span>\
						</div>\
						<div id="menuContent" class="menuContent" style="display:none; position:absolute; background-color: #f4f4f4; z-index: 4002;">\
							<ul id="parentTree" class="ztree"></ul>\
						</div>\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="name" class="col-sm-2 control-label">名称<span class="text-red">*</span></label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="name" name="name" placeholder="名称">\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="description" class="col-sm-2 control-label">简介</label>\
					<div class="col-sm-10">\
						<textarea class="form-control" rows="6" id="description" name="description" placeholder="简介"></textarea>\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="is_menu" class="col-sm-2 control-label">前台菜单</label>\
					<div class="col-sm-10">\
						<div id="type">\
							<input type="radio" name="is_menu" value="1" data-label="是" checked />\
							<input type="radio" name="is_menu" value="0" data-label="否" />\
						</div>\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="sort_order" class="col-sm-2 control-label">排序</label>\
					<div class="col-sm-10">\
						<input type="number" class="form-control" id="sort_order" name="sort_order" placeholder="排序" value="0" min="0" />\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="url" class="col-sm-2 control-label">访问链接</label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="url" name="url" placeholder="访问链接">\
					</div>\
				</div>\
				<div class="form-group rm-or-hide">\
					<label for="add_time" class="col-sm-2 control-label">添加时间</label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="add_time" name="add_time" placeholder="添加时间" />\
					</div>\
				</div>\
				<div class="form-group rm-or-hide">\
					<label for="update_time" class="col-sm-2 control-label">更新时间</label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="update_time" name="update_time" placeholder="更新时间" />\
					</div>\
				</div>\
				<div>\
					<input type="hidden" name="id" />\
				</div>\
			</div>\
			<div class="col-sm-5">\
				<div class="foo">\
					<p class="text-muted">1. 图片的尺寸为800*450</p>\
					<p class="text-muted">2. 标题根据页面是否显示而确定是否需要填入</p>\
					<p class="text-muted">3. 背景颜色主要用于轮播图片</p>\
					<p class="text-muted">4. 排序越小，实际显示越靠前</p>\
					<p class="text-muted">5. 链接地址可填入本系统的网站或课程链接地址（格式为wx/<path>.do）或其它任意可访问网址</p>\
					<p class="text-muted">6. 图片说明根据页面是否显示而确定是否需要填入</p>\
				</div>\
			</div>\
		</div>\
	</div>\
	<div class="tab-pane" id="c2">\
		<div class="row">\
			<div class="col-sm-7">\
				<div class="form-group">\
					<label for="seo_title" class="col-sm-2 control-label">SEO标题</label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="seo_title" name="seo_title" placeholder="SEO标题" />\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="seo_keywords" class="col-sm-2 control-label">SEO关键字</label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="seo_keywords" name="seo_keywords" placeholder="SEO关键字" />\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="seo_description" class="col-sm-2 control-label">SEO描述</label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="seo_description" name="seo_description" placeholder="SEO描述" />\
					</div>\
				</div>\
			</div>\
			<div class="col-sm-5">\
			</div>\
		</div>\
	</div>\
	<div class="tab-pane" id="c3">\
		<div class="row">\
			<div class="col-sm-7">\
				<div class="form-group">\
					<label for="model" class="col-sm-2 control-label">模型</label>\
					<div class="col-sm-10">\
					    <select class="form-control" id="model" name="model">\
						</select>\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="tpl_column" class="col-sm-2 control-label">栏目模版</label>\
					<div class="col-sm-10">\
					    <select class="form-control" id="tpl_column" name="tpl_column">\
						</select>\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="tpl_list" class="col-sm-2 control-label">列表模版</label>\
					<div class="col-sm-10">\
					    <select class="form-control" id="tpl_list" name="tpl_list">\
						</select>\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="tpl_single" class="col-sm-2 control-label">单页模版</label>\
					<div class="col-sm-10">\
					    <select class="form-control" id="tpl_single" name="tpl_single">\
						</select>\
					</div>\
				</div>\
			</div>\
			<div class="col-sm-5">\
			</div>\
		</div>\
	</div>\
	<div class="tab-pane" id="c4">\
		<div class="row">\
			<div class="col-sm-7">\
				<div class="form-group">\
					<label for="dirName" class="col-sm-2 control-label">目录名</label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="dirName" name="dir_name" placeholder="目录名">\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="is_html" class="col-sm-2 control-label">静态化</label>\
					<div class="col-sm-10">\
						<div id="isHtml">\
							<input type="radio" name="is_html" value="0" data-label="否" checked />\
							<input type="radio" name="is_html" value="1" data-label="是" />\
						</div>\
					</div>\
				</div>\
			</div>\
			<div class="col-sm-5">\
			</div>\
		</div>\
	</div>\
</div>\
';

/* CRUD 1: Create, 2: Read, 3: Update, 4: Delete */
var CREATE = 1, READ = 2, UPDATE = 3, DELETE = 4;
var validator = null;
function CRUDCategoryFunc(operCode, id, index) {
	var canOpen = false;
	var url;
	var obj;
	
	if (operCode == CREATE) {
		canOpen = true;
	} else if (operCode == READ || operCode == UPDATE) {
		url = kk.rootPath + '/Content/Category/find?id=' + id;
		obj = kk.getObj(url);
		if (obj != null) {
			canOpen = true;
		}
	} else if (operCode == DELETE) {
		url = kk.rootPath + '/Content/Category/delete?id=' + id;
		kk.deleteObj(url, xtt);
	} else {
		return false;
	}
	
	if (!canOpen) {
		return false;
	}
		
	$('.main-content').hide();
	$('.main-content').after(categoryDom);
	
	if (operCode == CREATE) {
		$('.box-title').empty().append('添加');

		$("input:radio[name='type']").change(function() {												// bind
			initCommonArea(operCode, parseInt($("input:radio[name='type']:checked").val()), null);
	    });
		initCommonArea(operCode, parseInt($("input:radio[name='type']:checked").val()), null);
	} else if (operCode == READ) {
		$('.box-title').empty().append('查看');
		$('.btnOK').hide();
		$('.btnCancel').text('关闭');

		initCommonArea(operCode, parseInt($("input:radio[name='type']:checked").val()), obj);
		$('#add_time').val(obj.add_time);
		$('#update_time').val(obj.update_time);

		$('#categoryForm').find(':input').attr("disabled", "disabled");						// 习惯性地处理
	} else if (operCode == UPDATE) {
		$('.box-title').empty().append('编辑');

		$("input:radio[name='type']").change(function() {												// bind
			initCommonArea(operCode, parseInt($("input:radio[name='type']:checked").val()), obj);
	    });
		initCommonArea(operCode, parseInt(obj.type), obj);
	}
	
	xrs("input:radio[name='type']", {
		xRsLabelClass: 'xrs-label-info',
	});
	
	$('.btnOK').off('click').on('click', function() {
 		if (validator.form() && doCU(operCode, id, index)) {
			$('.sub-content').remove();
			$('.main-content').show();
 		}
	});
	
	$('.btnCancel').off('click').on('click', function() {
		$('.sub-content').remove();
		$('.main-content').show();
	});
}

/* Create & Update */
/* CATEGORY TYPE 1: LIST, 2: SINGLE, 3: LINK */
var COLUMN = 1, LIST = 2, SINGLE = 3, LINK = 4;
function doCU(operCode, id, index) {
    var url;
    var method;
    var jsonObj = $('#categoryForm').serializeObject();
	var jsonStr = JSON.stringify(jsonObj);
//console.log('jsonStr = ' + jsonStr);
	var result;
	
	if (operCode == CREATE) {
	 	url = kk.rootPath + '/Content/Category/save';
		method = "POST";
		result = kk.doStrAjax(url, method, jsonStr);
		
	    if (result.code == 0) {
        	xtt.refresh();

	    	return true;
		}
	} else if (operCode == UPDATE) {
	 	url = kk.rootPath + '/Content/Category/update?id=' + id;
		method = "PUT";
		result = kk.doStrAjax(url, method, jsonStr);
		
	    if (result.code == 0) {
        	xtt.refresh();

	    	return true;
		}
	}
	
	return false;
}


/********************** initCommonArea ************************/
function initCommonArea(operCode, type, obj) {
	switch (type) {
	case COLUMN:
	case LIST:
	case SINGLE:
		$('#commonArea').empty().append(commonAreaDom);
		
		if (operCode == CREATE) {
			initTree();
			initModel();
			initTemplate();
			
			$('.rm-or-hide').remove();
		} else if (operCode == READ) {
			$('#categoryForm').setForm(obj);
			initTree(obj.id, obj.pid);
			initModel(obj.model);
			initTemplate(obj);
		} else if (operCode == UPDATE) {
			$('#categoryForm').setForm(obj);
			initTree(obj.id, obj.pid);
			initModel(obj.model);
			initTemplate(obj);

			$('.rm-or-hide').hide();
		}
		
		// 4 SINGLE
		if (type == COLUMN) {
			$('#tpl_list').empty().append('<option value="" selected></option>');
			$('#tpl_list').parent().parent().hide();
			$('#tpl_single').empty().append('<option value="" selected></option>');
			$('#tpl_single').parent().parent().hide();
		} else if (type == LIST) {
			$('#tpl_column').empty().append('<option value="" selected></option>');
			$('#tpl_column').parent().parent().hide();
		} else if (type == SINGLE) {
			$('#tpl_column').empty().append('<option value="" selected></option>');
			$('#tpl_column').parent().parent().hide();
			$('#tpl_list').empty().append('<option value="" selected></option>');
			$('#tpl_list').parent().parent().hide();
		}
		break;
	case LINK:
		$('#commonArea').empty().append(commonAreaDom);
		$('a[href="#c2"]').parent().hide();
		$('a[href="#c3"]').parent().hide();
		$('#c2').hide();
		$('#c3').hide();
//		$('a[href="#c2"').parent().remove();
//		$('a[href="#c3"').parent().remove();
//		$('#c2').remove();
//		$('#c3').remove();

		if (operCode == CREATE) {
			initTree();
			$('#c2').find(':input').val('');		// 防止切换类型赋值
			$('#c3').find(':input').val('');		// 防止切换类型赋值
			
			$('.rm-or-hide').remove();
		} else if (operCode == READ) {
			$('#categoryForm').setForm(obj);
			initTree(obj.id, obj.pid);
		} else if (operCode == UPDATE) {
			$('#categoryForm').setForm(obj);
//			$('#c2').resetForm();					// CAN'T WORK???
//			$('#c3').resetForm();
			$('#c2').find(':input').val('');
			$('#c3').find(':input').val('');
			initTree(obj.id, obj.pid);
			
			$('.rm-or-hide').hide();
		}
		break;
	default:
		break;
	}
	
	xrs("input:radio[name='is_menu']", {
		xRsLabelClass: 'xrs-label-info',
		iconEnable: true,
	});
	
	xrs("input:radio[name='is_html']", {
		xRsLabelClass: 'xrs-label-info',
		iconEnable: true,
	});
	
	validator = $("#categoryForm").validate({
		onfocusout: function(element) {
			$(element).valid();
		},
        rules: {
        	name: "required",
        },
        messages: {
        	name: "请输入标题",
        }
    });
}


/***** TREE ******/
/* initTree() */
function initTree(id, pid) {
	pid = pid === undefined ? 0 : pid;					// pid <==> 0
	
	var setting = {
		async: {
			enable: true,
			type: "get",
			url: kk.rootPath + '/Content/Category/getAll',
			autoParam: ["id", "name"],
			dataFilter: ajaxDataFilter
		},
		callback: {
			onClick: onClick,
			onAsyncSuccess: zTreeOnAsyncSuccess
		}, 
		data: {
			simpleData: {
				enable: true,
				idKey: "id",
				pIdKey: "pid",
				rootPId: 0
			},
			key: {
	            url: "xUrl"
	        }
		}
	};
	
	function ajaxDataFilter(treeId, parentNode, responseData) {
		var newData = new Array();
		var rootData = {
			id: 0,
			pid: -1,
			name: '根元素'
		};
		newData.push(rootData);
		
		var data = responseData.obj;
		for (var i = 0; i < data.length; i++) {
			if (data[i].id != id && data[i].pid != id) {
				newData.push(data[i]);
			}
		}
		
	    return newData;
	}
	
	function onClick(e, treeId, treeNode) {
		$('#pidName').val(treeNode.name);
		$('#pid').val(treeNode.id);
		return false;
	}
	
	function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {		// 加载成功后赋值
		var node = zTreeObj.getNodeByParam("id", pid);
		$('#pidName').val(node.name);
	}

	zTreeObj = $.fn.zTree.init($("#parentTree"), setting);
}


/****** initModel ******/
function initModel(model) {
	var url = kk.rootPath + '/Content/Model/getAll';
	var modelList = kk.getObj(url);
	
	var str = '';
	for (var i in modelList) {
		str += '<option value="' + modelList[i].table_name + ',' + modelList[i].name + '">' + modelList[i].name + '</option>';
	}
	$("#model").append(str);
	
	// set
	if (model) {
		$("#model").val(model);
	}
}


/****** initTemplate ******/
function initTemplate(obj) {
	var url = kk.rootPath + '/Asset/Template/getAllTpl4Cat';
	var templateList = kk.getObj(url);
	
	var str = '';
	for (var i in templateList) {
		str += '<option value="' + templateList[i] + '">' + templateList[i] + '.html' + '</option>';		// '.html'可能需要从后台获取
	}
	$("#tpl_column").append(str);
	$("#tpl_list").append(str);
	$("#tpl_single").append(str);
	
	// set
	if (obj) {
		$("#tpl_column").val(obj.tpl_column);
		$("#tpl_list").val(obj.tpl_list);
		$("#tpl_single").val(obj.tpl_single);
	}
}

/* batUpdateCatCache */
function batUpdateCatCache() {
	var xloading = xpopup.loading();
	
   	$.ajax({
   		type: 'PUT',
   		url: kk.rootPath + '/Content/Category/batUpdateCache',
   		data: null,
        dataType: 'json',
       	success: function(data) {
       		xloading.destroy();
       		
       		if (data.code == 0) {
       			xtt.refresh();
       			
		   		xpopup.notify({
		           	style: 'mini',
		           	type: 'success',
//		           	title: '操作成功',
   	                msg: data.msg,
					delay: 1000,
					position: 'center',
				});
   			}
       	}
   	});
}
